package com.jinzhi.jzyysweb.controller;


import cn.afterturn.easypoi.word.WordExportUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.config.Constant;
import com.jinzhi.common.utils.FileUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.common.utils.ZipUtil;
import com.jinzhi.jzweb.domain.CertificationBatchDO;
import com.jinzhi.jzweb.domain.StuSignUpDO;
import com.jinzhi.jzweb.service.CertificationBatchService;
import com.jinzhi.jzyysweb.domain.YysSignupDO;
import com.jinzhi.jzyysweb.pojo.YysSignupVO;
import com.jinzhi.jzyysweb.service.YysSignupService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * <pre>
 * 育婴师报名后端管理
 * </pre>
 * <small> 2021-05-14 14:23:14 | Long</small>
 */
@Controller
@RequestMapping("/jzweb/yysSignupWeb")
public class YysSignupController extends BaseController {

	@Value("${jinzhi.uploadUrl}") // 读取配置文件中的值
	String uploadUrl;

	@Value("${easypoi.path}")
	private String classPath;

	@Autowired
	private YysSignupService yysSignupService;
	@Autowired
	private UserService userService;
	@Autowired
	private CertificationBatchService certificationBatchService;


	//private final String uploadUrl = "D:/upload/";


	@GetMapping()
//	@RequiresPermissions("jzweb:yysSignup:yysSignup")
	String YysSignup(){
		return "jzyysweb/yysSignup/yysSignup";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:yysSignup:yysSignup")
	public Result<Page<YysSignupDO>> list(YysSignupDO yysSignupDTO){
		// 查询列表数据
		Wrapper<YysSignupDO> wrapper = new EntityWrapper<YysSignupDO>().orderBy("id" , false);
		if(StringUtil.notEmpty(yysSignupDTO.getAuthenticationId())){
			wrapper.eq("authentication_id",yysSignupDTO.getAuthenticationId());
		}
		if(yysSignupDTO.getStatus()!=null){
			wrapper.eq("status",yysSignupDTO.getStatus());
		}
		if(StringUtil.notEmpty(yysSignupDTO.getName())){
			wrapper.eq("name",yysSignupDTO.getName());
		}

		Page<YysSignupDO> page = yysSignupService.selectPage(getPage(YysSignupDO.class),wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			YysSignupDO obj = (YysSignupDO) page.getRecords().get(i);
			obj.setAuthenticationName(certificationBatchService.selectById(obj.getAuthenticationId()).getName());
			list.add(obj);
		}
		page.setRecords(list);
		return Result.ok(page);
	}

	@GetMapping("/add")
	@RequiresPermissions("jzweb:yysSignup:add")
	String add(){
		return "jzyysweb/yysSignup/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:yysSignup:edit")
	String edit(@PathVariable("id") Long id,Model model){
		YysSignupDO yysSignup = yysSignupService.selectById(id);
		model.addAttribute("yysSignup", yysSignup);
		return "jzyysweb/yysSignup/edit";
	}

	@Log("添加")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:yysSignup:add")
	public Result<String> save( YysSignupDO yysSignup){
		yysSignupService.insert(yysSignup);
		return Result.ok();
	}

	@Log("修改")
	@ResponseBody
	@RequestMapping("/review")
	@RequiresPermissions("jzweb:yysSignup:review")
	public Result<String>  review( @RequestParam("ids[]") Long[] ids,Integer state,String remark){
		int i = 0;
		for (Long id : ids) {
			YysSignupDO yysSignup = yysSignupService.selectById(id);
			yysSignup.setStatus(state);
			yysSignup.setExamineTime(new Date());
			yysSignup.setExamineUser(this.getUserId().toString());
			if(state==2){
				yysSignup.setRemark(remark);
			}else {
				yysSignup.setRemark("");
			}
			boolean b=yysSignupService.updateById(yysSignup);
			if(b){
				i++;
			}
		}
		if(i==ids.length){
			return Result.build(0,"已成功审核：" + i + "条数据");
		}else {
			return Result.fail("审核状态修改失败！");
		}

	}


	@Log("修改")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:yysSignup:edit")
	public Result<String>  update( YysSignupDO yysSignup){
		boolean update = yysSignupService.updateById(yysSignup);
		return update ? Result.ok() : Result.fail();
	}

	@Log("删除")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:yysSignup:remove")
	public Result<String>  remove( Long id){
		yysSignupService.deleteById(id);
		return Result.ok();
	}

	@Log("批量删除")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:yysSignup:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		yysSignupService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}



	@GetMapping("/exportWord")
	@RequiresPermissions("jzweb:yysSignup:resetPwd")
	@ResponseBody
	@Transactional
	public void  exportWord( HttpServletResponse response,String id) throws Exception {
		YysSignupDO yysSignupDO = yysSignupService.selectById(id);
		documentWordKssbb(response,"考生申报表.docx",yysSignupDO);
	}


	private File kssbTemplateFile(){
		File templateFile= new File(RootPath("/easypoi/kssbb.docx"));

		System.out.printf("++++++++++++++++++++++++++++++++++++++++++++++"+templateFile.getPath());

		return templateFile;
	}




	private void documentWordKssbb(HttpServletResponse response,String filename,YysSignupDO yysSignupDO) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//导出组装数据
		Map<String,Object> params =new HashMap<>();
		params.put("sbrxm",yysSignupDO.getName());//姓名

		params.put("xb",yysSignupDO.getSex());//性别
		params.put("csrq", sdf.format(yysSignupDO.getBirthTime()));//出生日期
		params.put("xlzy", yysSignupDO.getEducation());//学历
		params.put("zjlx","身份证");//证件类型
		params.put("sfzh",yysSignupDO.getIdNumber());//身份证号
		params.put("sjhm",yysSignupDO.getPhone());//手机号
		params.put("gzdw",yysSignupDO.getUnitName());//工作单位
		params.put("zy"," "); //职业
		params.put("dj",""); //等级	原职业等级
		params.put("zsbh",""); //证书编号
		params.put("nian"," "); //年
		params.put("yue"," ");//月
		params.put("ri"," ");//日
		params.put("fzjg"," ");//发证机构
		params.put("zczsmc"," ");//职称证书名称
		params.put("zczsdj"," ");//职称证书等级
		params.put("zczsbh"," ");//职称证书编号
		params.put("fznian"," ");//职称发证日期-年
		params.put("fzyue"," ");//职称发证日期-月
		params.put("fzri"," ");//职称发证日期-日
		params.put("fzjg"," ");//职称发证机构
		params.put("sbzy",yysSignupDO.getDeclaration());//申报职业
		params.put("sbdj",yysSignupDO.getDeclarationLevel());//申报等级
		params.put("csgw",yysSignupDO.getPostName());//岗位
		params.put("ljgz",yysSignupDO.getDeclarationPeriod());//累计工作年限  - 申报年限
		params.put("sbdh",yysSignupDO.getDeclaration());//申报职业
		params.put("zjgz",yysSignupDO.getDeclarationLevel());//申报等级
		params.put("gzdw",yysSignupDO.getUnitName());//原工作单位
		params.put("lxdh",yysSignupDO.getUnitPhone());//人事部门联系方式

		XWPFDocument word = WordExportUtil.exportWord07(kssbTemplateFile().getPath(),params);
		response.setHeader("content-disposition","attachment;filename="+new String(filename.getBytes(),"ISO8859-1"));
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//		response.setCharacterEncoding("UTF-8");
//		response.setContentType("application/json");
		word.write(response.getOutputStream());
	}




	/**
	 * 私有处理方法
	 */
	private String RootPath(String u_path) {
		String rootPath = "";
		//windows下
		if ("\\".equals(File.separator)) {
			//System.out.println(classPath);
			rootPath = classPath + u_path;
			rootPath = rootPath.replaceAll("/", "\\\\");
			if (rootPath.substring(0, 1).equals("\\")) {
				rootPath = rootPath.substring(1);
			}
		}
		//linux下
		if ("/".equals(File.separator)) {
			//System.out.println(classPath);
			rootPath = classPath + u_path;
			rootPath = rootPath.replaceAll("\\\\", "/");
		}
		return rootPath;
	}







	@Log("导出")
	@GetMapping( "/exportList")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:yysSignup:exportList")
	public void  exportList(HttpServletRequest request, HttpServletResponse response, String cbatchId) throws FileNotFoundException, UnsupportedEncodingException {
		List<YysSignupDO> list = yysSignupService.findByKv("authentication_id",cbatchId);
		for(YysSignupDO yysSignupDO : list){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Map<String,String> map = new HashMap<String,String>();
			map.put("{name}",yysSignupDO.getName());
			map.put("{sex}",yysSignupDO.getSex().equals("1")?"男":"女");
			map.put("{birthTime}",sdf.format(yysSignupDO.getBirthTime()));
			map.put("{education}",yysSignupDO.getEducation());
			map.put("{certificateNo}",yysSignupDO.getCertificateNo());
			map.put("{major}",yysSignupDO.getMajor());
			map.put("{idNumber}",yysSignupDO.getIdNumber());
			map.put("{unitName}",yysSignupDO.getUnitName());
			map.put("{ol}",yysSignupDO.getOccupationLevel());
			map.put("{wd}", sdf.format(yysSignupDO.getWorkDate()));
			map.put("{ocn}",yysSignupDO.getOriginalCertificateNo());
			map.put("{phone}",yysSignupDO.getPhone());
			map.put("{dp}",yysSignupDO.getDeclarationPeriod().toString()+"年");
			map.put("{address}",yysSignupDO.getAddress());
			map.put("{cn}",yysSignupDO.getDeclaration());
			map.put("{experience}",yysSignupDO.getExperience());
			map.put("{pe}","\n\n\n\n本人承诺从事申报职业工作"+yysSignupDO.getDeclarationPeriod().toString()+"年，以及所提交的身份材料（包括：身份证、户口本、学历毕业证、失业证等），相关证明材料等真实有效，如有不实，自愿承担成绩无效、证书撤消、失信记录等由此产生的一切后果。");
			map.put("{pic}",yysSignupDO.getImgUrl());
			String path= uploadUrl+"model/";
			if(yysSignupDO.getDeclarationLevel().equals("0")){
				path+="高级/";
			}else if(yysSignupDO.getDeclarationLevel().equals("1")){
				path+="中级/";
			}else{
				path+="初级/";
			}
			//默认正考
			if(!yysSignupDO.getCognizanceType().contains("正考")&&!yysSignupDO.getCognizanceType().contains("补考"))
				path+="正考/";
			else path+=yysSignupDO.getCognizanceType()+"/";
			if(yysSignupDO.getCognizanceSubject().contains("理论")&&yysSignupDO.getCognizanceSubject().contains("实操")){
				path+="3.docx";
			}else if(yysSignupDO.getCognizanceSubject().contains("实操")){
				path+="2.docx";
			}else {
				path+="1.docx";
			}
			wordOper(path,map,yysSignupDO.getSignSrc(),yysSignupDO.getCreateTime());
		}
		response.setHeader("content-type", "application/octet-stream");
		response.setCharacterEncoding("utf-8");
		// 设置浏览器响应头对应的Content-disposition
		//参数中 testZip 为压缩包文件名，尾部的.zip 为文件后缀
		response.setHeader("Content-disposition",
				"attachment;filename=" + new String("报名信息".getBytes("gbk"), "iso8859-1")+".zip");
		ZipUtil.toZip(uploadUrl+"word", false,response);
		File file = new File(uploadUrl+"word/");
		File[] files = file.listFiles();
		for(File f : files){
			f.delete();
		}
	}

	public void insertPic(XWPFParagraph p,String picUrl,int width,int height){
		try {
			InputStream in = null;
			if(picUrl.contains("http")){
				URL url = new URL(picUrl);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();//利用HttpURLConnection对象,我们可以从网络中获取网页数据.
				conn.setDoInput(true);
				in=conn.getInputStream();
				conn.connect();
				ByteArrayOutputStream output = new ByteArrayOutputStream();
				IOUtils.copy(in, output);
				ByteArrayInputStream byteInputStream = new ByteArrayInputStream(output.toByteArray());

				p.createRun().addPicture(byteInputStream, XWPFDocument.PICTURE_TYPE_JPEG, "", width, height);
				p.setAlignment(ParagraphAlignment.CENTER);
				in.close();
			}else{
				in = new FileInputStream(picUrl);
				byte[] ba = new byte[in.available()];
				in.read(ba);
				System.out.println(ba.length);
				ByteArrayInputStream byteInputStream = new ByteArrayInputStream(ba);
				p.createRun().addPicture(byteInputStream, XWPFDocument.PICTURE_TYPE_JPEG, "", width, height);
				in.close();
			}

		}catch (Exception e){
			e.printStackTrace();
		}
	}

	public void wordOper(String path,Map<String,String> map,String signSrc,Date date){
		XWPFDocument document = null;
		ByteArrayOutputStream ostream = null;
		try {
			if (path.endsWith("docx")) {
				FileOutputStream out = new FileOutputStream(uploadUrl+"word/"+map.get("{idNumber}")+map.get("{name}")+".docx");
				ostream = new ByteArrayOutputStream();
				document = new XWPFDocument(POIXMLDocument.openPackage(path));
				Iterator<XWPFTable> it = document.getTablesIterator();
				while(it.hasNext()){
					XWPFTable table = it.next();
					int rowNum = table.getNumberOfRows();
					for(int i=0;i<rowNum;i++){
						List<XWPFTableCell> cells = table.getRow(i).getTableCells();
						for(XWPFTableCell cell : cells){
							for(Map.Entry<String,String> e : map.entrySet()){
								if(cell.getText().contains(e.getKey())){
									if(e.getKey()=="{pic}"){
										cell.removeParagraph(0);
										XWPFParagraph p = cell.addParagraph();
										insertPic(p,e.getValue(),1094400,1461600);
										p.setAlignment(ParagraphAlignment.CENTER);
										break;
									}
									String text = e.getValue();
									cell.removeParagraph(0);
									cell.setText(text);
									if(i==8){
										XWPFParagraph p = cell.addParagraph();
										p.setAlignment(ParagraphAlignment.RIGHT);
										p.createRun().setText("申报人签名：");
										insertPic(p,signSrc,680400,201600);
										p.createRun().setText("\n\n\n\n\n\n\n");
										p.setAlignment(ParagraphAlignment.RIGHT);
										p.setVerticalAlignment(TextAlignment.CENTER);
									}else if(i==9){
										XWPFParagraph p1 = cell.addParagraph();
										p1.setAlignment(ParagraphAlignment.RIGHT);
										p1.createRun().setText("承诺人：");
										insertPic(p1,signSrc,680400,201600);
										p1.createRun().setText("\n\n\n\n\n\n\n");
										p1.setAlignment(ParagraphAlignment.RIGHT);
										p1.setVerticalAlignment(TextAlignment.CENTER);
										XWPFParagraph p2 = cell.addParagraph();
										p2.setAlignment(ParagraphAlignment.RIGHT);
										SimpleDateFormat sdf = new SimpleDateFormat("YYYY年MM月dd日");
										p2.createRun().setText(sdf.format(date)+"\n\n\n\n\n\n\n\n\n\n\n\n");
									}
									cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
									break;
								}
							}

						}
					}
				};
				document.write(ostream);
				out.write(ostream.toByteArray());
				out.close();
				ostream.close();

			} else {
				System.out.println("此文件不是word文件！");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args){
		String uploadUrl = "D:/upload/";
		String path = uploadUrl+"model/paper.docx";
		XWPFDocument document = null;
		ByteArrayOutputStream ostream = null;
		try {
			if (path.endsWith("docx")) {
				FileOutputStream out = new FileOutputStream(uploadUrl+"word/1.docx");
				ostream = new ByteArrayOutputStream();
				document = new XWPFDocument(POIXMLDocument.openPackage(path));
				List<XWPFParagraph> it = document.getParagraphs();
				for(int i=0;i<10;i++){
					XWPFParagraph x=document.createParagraph();
					x.createRun().setText((i+1)+".123");
					document.createParagraph().createRun().setText("A.123       B.123");
					document.createParagraph().createRun().setText("B.123       D.123");
				}
				document.write(ostream);
				out.write(ostream.toByteArray());
				out.close();
				ostream.close();

			} else {
				System.out.println("此文件不是word文件！");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
